// Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __REDIS_HANDLER_H__
#define __REDIS_HANDLER_H__

#include "RrConfig.h"
#include <hiredis/hiredis.h>
#include <string>
#include <vector>
#include <memory>

using namespace std;

enum {
    M_REDIS_OK = 0,
    M_CONNECT_FAIL = -1,
    M_CONTEXT_ERROR = -2,
    M_REPLY_ERROR = -3,
    M_EXE_COMMAND_ERROR = -4
};

class RedisHandler {
public:
    RedisHandler();

    ~RedisHandler();

    int connect(const string &addr, int port, const string &pwd = "");
    int disConnect();
    void free();
    int setValue(const string &key, const string &value);
    int getValue(const string &key, string &value);
    int delKey(const string &key);
    int findKeys(std::vector<std::string> &keys, string &cmd);
    int findValues(std::vector<std::string> &values, string &cmd);
    int findAllKeys(std::vector<std::string> &keys);
    int tryLock(const string &key, const string &value, int expireTime);

    int printAll();
    string getErrorMsg();

    int reConnectCnt;
private:
    string m_addr;
    int m_port;
    string m_pwd;
    redisContext *pm_rct;
    redisReply *pm_rr;
    string error_msg;

    int connectAuth(const string &pwd);
    int handleReply(void *value = NULL, redisReply ***array = NULL);
};

#endif

typedef enum{
    MIAN_PTHREAD,
    HEARTBEAT_PTHREAD,
    
}PTHREADID_TYPE;

class RedisOperator{
public:
    static RedisOperator& GetInstance(){
        static RedisOperator gRedis;
        return gRedis;
    }
    RedisOperator();
    ~RedisOperator();
    
    int connect(const string &addr, int port, const string &pwd);

    int setValue(const string &key, const string &value);

    int getValue(const string &key, string &value);

    int delKey(const string &key);

    int findKeys(std::vector<std::string> &keys, string &cmd);

    int findValues(std::vector<std::string> &keys, string &cmd);

    int findAllKeys(std::vector<std::string> &keys);

    int tryLock(const string &key, const string &value, int expireTime = 5);

    void free();

    std::shared_ptr<RedisHandler> pRedis;
};